package xyz.xiangyushui.controller.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import xyz.xiangyushui.dao.user.member.MembershipDao;
import xyz.xiangyushui.javaBean.user.Role;
import xyz.xiangyushui.javaBean.user.User;

public class UserFilter {
	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain,Role role) throws IOException, ServletException {
		HttpSession session=((HttpServletRequest)request).getSession(false);
		if(session==null){
			toLoginPage(request, response);
			return;
		}else{
			if(session.getAttribute("user")==null||((User)session.getAttribute("user")).getRole()!=role){
				toLoginPage(request, response);
				return;
			}else if(((User)session.getAttribute("user")).getRole()==Role.member){
				MembershipDao md=new MembershipDao();
				switch(md.getState(((User)session.getAttribute("user")).getName())){
				case 0:
					((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath()+"/active");
					return;
				case 2:
					((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath()+"/stop");
					return;
				}
			}
		}
		chain.doFilter(request, response);
	}

	private void toLoginPage(ServletRequest request, ServletResponse response){
		try {
			((HttpServletResponse)response).sendRedirect(((HttpServletRequest)request).getContextPath()+"/login");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
